package com.yuma.pandc;

import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.ThreadLocalRandom;

class NumberContainer {
    // 维护的容器
    List<Integer> container = new ArrayList<>();
    int maxSize = 3;

    public synchronized void push(int num){
        while (container.size() == maxSize){
            try {
                this.wait();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
        // 基本类型转成包装类型：自动装箱
        container.add(num);
        System.out.println(Thread.currentThread().getName() + " push " + num);
        this.notifyAll();
    }

    public synchronized void pop(){
        while (container.size() == 0){
            try {
                this.wait();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
        Integer num = container.remove(0);
        System.out.println(Thread.currentThread().getName() + " pop " + num);
        this.notifyAll();
    }
}


public class ProdAndCons {
    public static void main(String[] args) {
        NumberContainer container = new NumberContainer();

        for(var i = 0; i < 5; i++){
            new Thread(() -> {
                container.push(ThreadLocalRandom.current().nextInt(10));
            }, "push"+i).start();
        }

        for(var i = 0; i < 5; i++){
            new Thread(() -> {
                container.pop();
            }, "pop"+i).start();
        }
    }
}
